package com.rzhkj.base.interceptor;

import com.rzhkj.box.entity.Box;
import com.rzhkj.box.entity.BoxStateEnum;
import com.rzhkj.box.service.BoxSV;
import com.rzhkj.core.base.JwtToken;
import com.rzhkj.core.common.Constants;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * LoginInterceptor
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);


    @Resource
    private BoxSV boxSV;

    /**
     * 1.验证apikey 的合法性
     * 2.验证token的正确性和实效性
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.验证apikey,apisecret 的合法性
        String apiKey = request.getHeader(Constants.ApiKey.val.toString());
        Map<String, Object> params = new HashedMap();
        params.put("apiKey", apiKey);
        Box box = boxSV.load(params);
        if (box == null || box.getState().equals(BoxStateEnum.Disenable.name())) {
            return false;
        }
        //2.验证token的正确性和实效性
        //获得body
        String requestBody = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        requestBody = stringBuilder.toString();
        boolean verify = new JwtToken()
                .secret(box.getApiSecret())
                .secret(requestBody)
                .verifier();
        if (!verify) {
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}